package com.xiaolin.oa.aspect;

import com.xiaolin.oa.annotations.DataPerm;
import com.xiaolin.oa.exception.ServiceException;
import com.xiaolin.oa.model.entity.BaseEntity;
import com.xiaolin.oa.service.SysOrganizationService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.StringJoiner;

/**
 * @author xiaolin
 * @description 数据权限切面
 * @since 2024/8/12
 */
@Aspect
@Component
public class DataPermAspect {
    @Autowired
    private SysOrganizationService organizationService;

    /**
     * 封装数据权限SQL
     *
     * @param joinPoint
     * @param dataPerm
     */
    @Before("@annotation(dataPerm)")
    public void permCheck(JoinPoint joinPoint, DataPerm dataPerm) {
        int argIndex = dataPerm.argIndex();
        String orgAlias = dataPerm.orgAlias();
        BaseEntity baseEntity ;
        try {
            baseEntity = (BaseEntity) joinPoint.getArgs()[argIndex];
        } catch (Exception e) {
            e.printStackTrace();
            ServiceException.error("数据权限参数解析错误");
            return;
        }
        StringJoiner sj = new StringJoiner(",", "(", ")");
        List<Integer> orgDataPerms = organizationService.getUserOrgDataPerms();
        if (CollectionUtils.isEmpty(orgDataPerms)) {
            orgDataPerms.add(-1);
        }
        for (Integer orgId : orgDataPerms) {
            sj.add(String.valueOf(orgId));
        }
        String dataPermSql = "and " + orgAlias + ".id in " + sj;
        baseEntity.setDataPermSql(dataPermSql);
    }
}
